package com.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.UUID;

/**
 * 全局过滤器
 * 用于记录请求日志和添加链路跟踪ID
 */
@Component
@Slf4j
public class GlobalTraceFilter implements GlobalFilter, Ordered {

    private static final String TRACE_ID = "X-Trace-Id";
    private static final String START_TIME = "startTime";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 记录请求开始时间
        exchange.getAttributes().put(START_TIME, System.currentTimeMillis());

        // 生成并添加跟踪ID
        String traceId = UUID.randomUUID().toString().replace("-", "");
        ServerHttpRequest request = exchange.getRequest().mutate()
                .header(TRACE_ID, traceId)
                .build();

        // 记录请求日志
        log.info("请求开始: {} {}, traceId: {}, IP: {}", 
                request.getMethod(), 
                request.getURI(), 
                traceId,
                request.getRemoteAddress().getHostString());

        return chain.filter(exchange.mutate().request(request).build())
                .then(Mono.fromRunnable(() -> {
                    // 计算请求处理时间
                    Long startTime = exchange.getAttribute(START_TIME);
                    if (startTime != null) {
                        long duration = System.currentTimeMillis() - startTime;
                        log.info("请求结束: {} {}, traceId: {}, 状态码: {}, 耗时: {}ms",
                                request.getMethod(),
                                request.getURI(),
                                traceId,
                                exchange.getResponse().getStatusCode(),
                                duration);
                    }
                }));
    }

    @Override
    public int getOrder() {
        // 确保在所有过滤器之前执行
        return Ordered.HIGHEST_PRECEDENCE;
    }
} 